<?php

namespace App\Service\Pay;

use App\Models\Bank;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Exception;

class DzPayService extends PayService implements Pay
{
    /**
     * 充值通知地址
     * @var string
     */
    protected string $pay_notify_url = '/api/v1/dz_recharge';

    /**
     * 代付通知地址
     * @var string
     */
    protected string $withdrawal_notify_url = '/api/v1/dz_withdrawal';


    //充值
    public function recharge($attach = [])
    {
        try {
            $this->setReturnUrl();
            $param = [
                'version' => '1.0',
                'mch_id' => $this->merchant,
                'notify_url' => url($this->pay_notify_url),
                'page_url' => $this->return_url,
                'mch_order_no' => $this->order->no,
                'pay_type' => $this->pay_code,
                'trade_amount' => $this->order->amount,
                'order_date' => Carbon::now()->toDateTimeString(),
                'goods_name' => 'recharge',
            ];
            if (isset($attach['bank_code']) && !empty($attach['bank_code'])){
                $param['bank_code'] = $attach['bank_code'];
            }

            $param['sign'] = $this->sign($param, $this->pay_key);
            $param['sign_type'] = 'MD5';
            $response = Http::asForm()->post($this->pay_url, $param);
            $result = json_decode($response->body(), true);
            $this->order->param = json_encode($param, JSON_UNESCAPED_UNICODE);
            $this->order->response = json_encode($result, JSON_UNESCAPED_UNICODE);
            if (isset($result['respCode']) && $result['respCode'] == 'SUCCESS' && isset($result['tradeResult']) && $result['tradeResult'] == '1') {
                $this->order->payment_no = $result['orderNo'];
                $this->order->save();
                return $result['payInfo'];
            }
            $this->rechargeFail();
            return false;
        } catch (Exception $exception) {
            $error_message = json_encode(['msg' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], JSON_UNESCAPED_UNICODE);
            $this->rechargeFail($error_message);
            return false;
        }
    }

    public function withdrawal($attach = [])
    {
        try {
            $card = json_decode($this->order->card, true);
            $bank_code = 'IDPT0001';
            $param = [
                'mch_id' => $this->merchant,
                'mch_transferId' => $this->order->no,
                'transfer_amount' => intval($this->order->actual_amount),
                'apply_date' => Carbon::now()->toDateTimeString(),
                'bank_code' => $bank_code,
                'receive_name' => $card['username'],
                'receive_account' => $card['number'],
                'remark' => $card['ifsc'],
                'back_url' => url($this->withdrawal_notify_url),
            ];
            $param['sign'] = $this->sign($param, $this->withdrawal_key);
            $param['sign_type'] = 'MD5';
            $response = Http::asForm()->post($this->withdrawal_url, $param);
            $result = json_decode($response->body(), true);
            $result = is_array($result) ? $result : [];
            //记录入参跟响应
            $state = isset($result['respCode']) && $result['respCode'] == 'SUCCESS';
            $this->withdrawalCallback($param, $result, $result['tradeNo'] ?? '', $state);
            $this->order->save();
        } catch (Exception $exception) {
            $this->withdrawalCallback([], ['msg' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], '', false);
        }
    }


    /**
     * 签名
     * @param $data
     * @param $secret
     * @return string
     */
    protected function sign($data, $secret): string
    {
        ksort($data);
        $str = '';
        foreach ($data as $key => $val) {
            if ($val != null) {
                $str .= $key . '=' . $val . '&';
            }
        }
        return strtolower(md5($str . 'key=' . $secret));
    }

    /**
     * 验签
     * @param array $params
     * @param string $type
     * @return bool
     */
    public function checkSign(array $params, string $type): bool
    {
        $sign = $params['sign'];
        // 验证签名参数是否正确
        unset($params['sign'], $params['signType'], $params['merRetMsg']);
        return $sign == $this->sign($params, $type == 'pay' ? $this->pay_key : $this->withdrawal_key);
    }

}
